﻿using System;
using System.Runtime.Serialization;
using System.Xml;

namespace ProLinq.Wcf.Runtime
{
	class SharedTypeResolver : DataContractResolver
	{
		private DataContractResolver _originalResolver;

		public SharedTypeResolver(DataContractResolver original)
		{
			this._originalResolver = original;
		}

		public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
		{
			var fallbackResolver = this._originalResolver ?? knownTypeResolver;
			return fallbackResolver.ResolveName(typeName, typeNamespace, declaredType, knownTypeResolver) ?? Type.GetType(typeName + ", " + typeNamespace);
		}

		public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out System.Xml.XmlDictionaryString typeName, out System.Xml.XmlDictionaryString typeNamespace)
		{
			var fallbackResolver = this._originalResolver ?? knownTypeResolver;
			if (!fallbackResolver.TryResolveType(type, declaredType, knownTypeResolver, out typeName, out typeNamespace))
			{
				var dictionary = new XmlDictionary();
				typeName = dictionary.Add(type.FullName);
				typeNamespace = dictionary.Add(type.Assembly.FullName);
			}
			return true;
		}
	}
}
